import { message, Modal, PaginationProps, Space, Spin, Table } from "antd";
import { Fragment, useState } from "react";
import { IUpdateAccount } from "../../api";
import { AccountType, IAccount } from "../../interface";
import AccountCommit, { IFormData } from "../accountCommit";

const { Column } = Table;

interface IAccountTableProps {
    data: IAccount[]
    total: number
    pageSize?: number
    canOperate?: boolean
    handleDelete?: (account: IAccount) => Promise<boolean>
    handleUpdate?: (account: IUpdateAccount) => Promise<boolean>
    handlePageChange: (page: number) => void
}

const AccountTable: React.FC<IAccountTableProps> = (props) => {
    let { pageSize, canOperate } = props;
    pageSize = pageSize || 8;
    canOperate = canOperate || true

    const { handleDelete, handleUpdate, handlePageChange } = props;
    const { data, total } = props;

    if (canOperate && (!handleDelete || !handleUpdate)) {
        throw new Error('参数错误,请传入操作处理函数');
    }

    const [loading, setLoading] = useState(false);
    const [currentPage, setCurrentPage] = useState(1);
    

    // 点击修改出现弹框
    const updateHandler = (account: IAccount) => {
        // 在modal无法获取数据,将数据处理传入组件,组件中进行确认,调用此处处理函数
        const onOk = async (data: IFormData) => {
            // 加载弹出框,防止多次点击
            modal.update(pre => ({
                ...pre,
                content: (
                    <Fragment>
                        <Spin className="loading" />
                        <AccountCommit account={account} submitFrom={onOk} cancel={onCancel} />
                    </Fragment>
                ),
            }))

            let date_time = new Date(data.date_time.toDate());
            let account_type = data.account_type ? AccountType.expend : AccountType.income;
            await postUpdate({...data, account_type, date_time})
            modal.destroy();
        }
        const onCancel = () => {
            modal.destroy();
        }

        const modal = Modal.confirm({
            icon: '',
            content: (
                <Fragment>
                    <AccountCommit account={account} submitFrom={onOk} cancel={onCancel} />
                </Fragment>
            ),
            cancelButtonProps: {style: {display: 'none'}},
            okButtonProps: {style: {display: 'none'}},
        });
    }
    // 修改弹框确认修改
    const postUpdate = async (params: IUpdateAccount) => {
        // console.log(params)
        setLoading(true);
        let result = handleUpdate && await handleUpdate(params);
        setLoading(false);
        if (result) {
            message.success('修改成功');
        }
        else {
            message.error('修改失败');
        }
    }

    // 点击删除出现弹框
    const deleteHandler = (account: IAccount) => {
        const onOk = () => {
            // 加载弹出框,防止多次点击
            modal.update(pre => ({
                ...pre,
                content: (
                    <div>
                        <Spin className="loading" /> 
                        确定删除此数据吗？
                    </div>
                ),
            }))
            postDelete(account)
        }
        const modal = Modal.confirm({
            content: (
                <div>
                    确定删除此数据吗？
                </div>
            ),
            onOk: onOk 
        })
    }
    // 删除弹框确认删除
    const postDelete = async (account: IAccount) => {
        // console.log(account)
        setLoading(true);
        let result = handleDelete && await handleDelete(account);
        setLoading(false);
        if (result) {
            message.success('修改成功');
        }
        else {
            message.error('修改失败');
        }
    }
    // 翻页
    const pageChange: PaginationProps['onChange'] = async (page, pageSize) => {
        setLoading(true);
        await handlePageChange(page);
        setLoading(false);

        setCurrentPage(page);
    }

    return (
        <Table dataSource={data} rowKey={(record: IAccount) => record.account_id} loading={loading}
            pagination={{
                current: currentPage,
                pageSize,
                total: total,
                showTotal: total => `共${total}条数据`,
                showSizeChanger: false,
                onChange: pageChange
            }}
        >
            <Column title="日期" width={120} render={(_: any, record: IAccount) => (
                <span>{ new Date(record.date_time).toLocaleDateString() }</span>
            )} />
            <Column title="金额" width={100} key="amount" render={(_: any, record: IAccount) => (
                <span>
                    { record.account_type === '收入' ? `+` : `-` }
                    { record.amount }
                </span>
            )} />
            <Column title="分类" width={80} render={(_: any, record: IAccount) => (
                <span>{ record.category_name }</span>
            )} />
            <Column title="备注" render={(_: any, record: IAccount) => (
                <span>{ record.notes }</span>
            )} />
            {
                canOperate ? 
                    <Column title="操作" width={120} render={(_: any, record: IAccount) => (
                        <Space size="middle">
                            <a onClick={() => updateHandler(record)}>修改</a>
                            <a onClick={() => deleteHandler(record)}>删除</a>
                        </Space>
                    )} />
                    : ''
            }
            
        </Table>
    )
}

export default AccountTable;


